/*
 * Alarm.c
 *
 *  Created on: Mar 12, 2012
 *      Author: mikaelgra
 */

#include <stdlib.h>
#include <string.h>

#include "Alarm.h"

/**
 * Constructs a new Alarm and places it on the heap. Before this goes
 * out of scope Alarm_Finalize() must be called on the returned alarm.
 *
 * @param name
 * 		This is the name of the alarm
 * @param twitterMessage
 * 		This is the message that will be displayed on twitter
 * @param password
 * 		This is the password that is needed to disarm is the alarm
 * @param triggerTime
 * 		This is the time it takes from the alarm is in triggered state
 * 		until it goes into the started state
 * @param triggerValue
 * 		This is the value the GPIO pin should have for it to trigger
 * @param gpioPin
 * 		This is the GPIO pin that will be used
 *
 * @return
 * 		This is the newly constructed alarm.
 */
struct stAlarm_t* Alarm_New(
		char *name,
		char *twitterMessage,
		char *password,
		int triggerTime,
		int triggerValue,
		int gpioPin)
{
	struct stAlarm_t *alarm = (struct stAlarm_t*)malloc(sizeof(struct stAlarm_t));
	alarm->enAlarmState = eEnabled;
	alarm->gpioPin = gpioPin;
	alarm->triggerTime = triggerTime;
	alarm->triggerValue = triggerValue;
	alarm->timeSinceTrigger = 0;

	// these 3 needs special treatment since they are pointers
	int length = strlen(twitterMessage) + 1;
	alarm->twitterMessage = (char*)malloc(length * sizeof(char));
	int i;
	for(i = 0; i < length; i++)
	{
		*(alarm->twitterMessage + i) = *(twitterMessage + i);
	}

	length = strlen(password) + 1;
	alarm->password = (char*)malloc(length * sizeof(char));
	for(i = 0; i < length; i++)
	{
		*(alarm->password + i) = *(password + i);
	}

	length = strlen(name) + 1;
	alarm->name = (char*)malloc(length * sizeof(char));
	for(i = 0; i < length; i++)
	{
		*(alarm->name + i) = *(name + i);
	}

	return alarm;
}

/**
 * Destructs the the alarm, freeing up the heap memory.
 *
 * @param alarm
 * 		This is the alarm to be destructed.
 */
void Alarm_Finalize(struct stAlarm_t* alarm)
{
	if(alarm->name != NULL)
	{
		free(alarm->name);
	}
	if(alarm->password != NULL)
	{
		free(alarm->password);
	}
	if(alarm->twitterMessage != NULL)
	{
		free(alarm->twitterMessage);
	}
	free(alarm);
}
